<template>
	<view>
		<text>{{ message }}</text>
		<input v-model="inputMessage" placeholder="请输入消息" />
		<button @tap="sendMessage">发送消息</button>
	</view>
</template>

<script>
	import config from '../../common/config'
	export default {
		data() {
			return {
				message: '',
				inputMessage: '',
				socket: null,
				To: '111111'
			};
		},
		mounted() {
			this.socket = uni.connectSocket({
				url: 'ws://localhost:9090/websocket/' + '333333',
				complete: () => {
					console.log('WebSocket连接成功');
				},
			});

			this.socket.onMessage((res) => {
				// console.log('收到消息:', res.data);
				let message = JSON.parse(res.data);
				console.log(message);
				this.message = res.data;
			});

			this.socket.onClose(() => {
				console.log('WebSocket连接已关闭');
			});
		},
		methods: {
			sendMessage() {
				if (this.inputMessage.trim() === '') {
					uni.showToast({
						title: '消息不能为空',
						icon: 'none',
					});
					return;
				}

				const message = {
					messageType: 4,
					textMessage: this.inputMessage,
					username: '333333',
					to: this.To
				};
				uni.request({
					url: config.baseUrl + 'chat/updateMessage',
					method: 'POST',
					data: {
						textMessage: this.inputMessage,
						messageType: 4,
						toUserName: this.To,
						fromUsername: '333333'
					},
					success: (res) => {
						console.log(res);
					}
				})
				this.socket.send({
					data: JSON.stringify(message),
					success: () => {
						console.log('消息发送成功');
						this.inputMessage = '';
					},
				});
			},
		},
		beforeDestroy() {
			this.socket.close();
		},
	};
</script>